package com.lc.stock.module.crawldata.impl;

import com.alibaba.fastjson.JSONArray;
import com.lc.stock.common.CrawDataAPI;
import com.lc.stock.module.crawldata.AbstractCrawData;
import com.lc.stock.module.floatingstockholder.dao.FloatingStockholderDao;
import com.lc.stock.module.floatingstockholder.domain.FloatingStockholder;
import com.lc.stock.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lichen
 * @description 抓取公司十大流通股 数据
 * @menu
 * @date 2023/2/7 9:09
 */
@Slf4j
@Service
public class CrawFloatingStockholderService extends AbstractCrawData {

    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private FloatingStockholderDao floatingStockholderDao;

    /**
     * 抓取公司十大流通股 数据
     * @param stockCode
     */
    @Override
    public void doCraw(String stockCode) {
        try{
            String resp = httpClientUtil.get(CrawDataAPI.FLOATING_STOCKHOLDER.getUrl(), stockCode);
            List<FloatingStockholder> floatingStockholders = JSONArray.parseArray(resp, FloatingStockholder.class);
            List<FloatingStockholder> list = floatingStockholders.stream().map(item -> item.setStockCode(stockCode)).collect(Collectors.toList());

            //先删除当前股票的数据，再批量新增
            floatingStockholderDao.deleteByStockCode(stockCode);
            floatingStockholderDao.saveAll(list);
        }catch(Exception e){
            log.error("抓取公司" + stockCode + "十大流通股东数据失败",e);
        }
    }

    @Override
    public String getSubClassName() {
        return this.getClass().getName();
    }
}
